// *********************************************************
//      Copyright (c) Kosta Gaitanis
//      All rights reserved
//
//      k.gaitanis@gmail.com
//
// *********************************************************

#include "Sphere.h"

Sphere::Sphere(double radius, int spacing, const QString &name) :
    Item(name)
{
    if (90 % spacing != 0) {
        qDebug() << "90/spacing must be an integer. Setting to 10.";
        spacing = 10;
    }
    if (radius <= 0.0) {
        qDebug() << "radius must be positive";
        radius = 1.0;
    }

    /* FIXME complete the code */
    createSphere(radius, spacing);
    /* STOP here */
}

void Sphere::onFrameChanged(double frame)
{
    Q_UNUSED(frame);
    /* FIXME complete the code */
    // (optional)
    // apply a transformation matrix on this item using setGLTransform()
    //Matrix m = Matrix::rotation(frame/50, frame/20, frame/5, frame/10);
    //setTransform(m);
    // and frame to make the cube move.
    /* STOP here */
}

void Sphere::createSphere(double radius, int spacing)
{
    //START//
    double theta, phi, rTheta, rPhi, rPhi2;

    //Creer spacing pour latitude et longtitude
    double spacing_longtitude = (double)spacing/180.0;
    double  spacing_latitude = (double)spacing_longtitude/2.0;

    //Pour coordinate des vector texture
    double ty0 = 0.0; //Y dessus
    double ty1 = 0.0; //Y dessous
    double tx; //X

    for( phi = -90; phi <= 90 - spacing; phi+=spacing){
        Face triangles(Face::TriangleStrip);

        ty0 = ty1; //Y0 actuel = Y1 du point dernier
        ty1 += spacing_longtitude;

        rPhi = phi / 180.0 * M_PI;
        rPhi2 = (phi + spacing) / 180.0 * M_PI;

        //Reset coordinate X pour latitude suivante
        tx = 0.0;
        for( theta = 0; theta <= 360; theta+=spacing){
            rTheta = theta / 180.0 * M_PI;

            Vector n0 = Matrix::rotationZ(rTheta) * Matrix::rotationY(rPhi) * Vector::ORTHO_X;
            Vector n1 = Matrix::rotationZ(rTheta) * Matrix::rotationY(rPhi2) * Vector::ORTHO_X;

            Vector v0 = n0 * radius;
            Vector v1 = n1 * radius;

            //Creer vector texture pour une latitude
            Vector t0(-tx, ty0, 0.0);
            Vector t1(-tx, ty1, 0.0);

            //Ameliorer tx pour longtitude suivant de cette latitude
            tx += spacing_latitude;

            triangles.addPoint(v0, n0, t0);
            triangles.addPoint(v1, n1, t1);
        }
        //Ajouter le face pour cet item
        this->addFace(triangles);
    }
}

